import hashlib
import logging

logger = logging.getLogger("wechat.helper.meituan")


class SignHelper(object):
    """
    签名计算工具类
    """
    @staticmethod
    def get_sign(params, secret):
        encode_str = SignHelper.get_encode_str(params, secret)
        logger.info(f"encode_str={encode_str}")
        sign = SignHelper.generate_sign(encode_str)
        return sign

    @staticmethod
    def get_encode_str(params, secret):
        data = sorted(params.items(), key=lambda asd: asd[0], reverse=False)
        str_a = ""
        for item in data:
            k = item[0]
            v = item[1]
            if (v and k!="sign") or (v==0 and k!="sign"):
                str_a += k + str(v)
        str_temp = secret + str_a
        return str_temp

    @staticmethod
    def generate_sign(content):
        return SignHelper.sha1(content.encode()).lower()

    @staticmethod
    def sha1(text=None):
        """
        sh1加密
        :param text: 需要传入bytes类型,否则返回空串
        :return: 返回加密后的字符串
        """
        if text is None:
            return ''
        if isinstance(text, bytes):
            m = hashlib.sha1()
            m.update(text)
            return m.hexdigest()
        return ''


if __name__ == '__main__':
    secret = "test"
    params = dict(
        appkey="test",
        timestamp = 1477395862,
        version = 1.0,
        number=123,
        string="测试",
        double =123.123,
        boolean="true",
        empty="",
    )
    sign = SignHelper.get_sign(params, secret)
    print(f"sign={sign}")